package services

import (
	log "github.com/sirupsen/logrus"
	"go_anime_picture_api/models/gitee"
	"go_anime_picture_api/models/picture"
	"go_anime_picture_api/utils"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

const (
	MLTDCardGiteeUrl    = "https://gitee.com/api/v5/repos/anime_picture/mltd-card/contents/card?access_token=16a415e183b8a8da461db30b8ee0ff83&ref=master"
	MLTDBigCardGiteeUrl = "https://gitee.com/api/v5/repos/anime_picture/mltd-card/contents/big-card?access_token=16a415e183b8a8da461db30b8ee0ff83&ref=master"
	MLTDBgGiteeUrl      = "https://gitee.com/api/v5/repos/anime_picture/mltd-card/contents/bg?access_token=16a415e183b8a8da461db30b8ee0ff83&ref=master"
)

// 构建数据库（暂时用list代替）
func BuildMLTDInfos() {
	ReBuildMLTDInfos()
}

// 重构数据库（暂时用list代替）
func ReBuildMLTDInfos() {

	rand.Seed(time.Now().UnixNano())

	picture.MLTDCardInfos = picture.MLTDCardInfoList{}
	cardInfos := GetFileInfos(MLTDCardGiteeUrl)
	dealMLTDCardInfoByGitee(&cardInfos, &picture.MLTDCardInfos)

	picture.MLTDCardInfos = picture.MLTDCardInfoList{}
	bigCardInfos := GetFileInfos(MLTDBigCardGiteeUrl)
	dealMLTDCardInfoByGitee(&bigCardInfos, &picture.MLTDBigCardInfos)

	picture.MLTDBgInfos = picture.MLTDBgInfoList{}
	bgInfos := GetFileInfos(MLTDBgGiteeUrl)
	dealMLTDBgInfoByGitee(&bgInfos, &picture.MLTDBgInfos)

	log.Infoln("构建MLTDk卡牌图片数据库完成")
}

func dealMLTDCardInfoByGitee(infos *gitee.FileInfoList, cardInfos *picture.MLTDCardInfoList) {
	for _, info := range *infos {
		cardFullName := info.Name
		cardName, _ := utils.GetFileNameAndExt(cardFullName)

		cardNameInfo := strings.Split(cardName, "-")
		id, _ := strconv.Atoi(cardNameInfo[1])
		cardInfo := picture.MLTDCardInfo{
			Name:       cardFullName,
			Id:         id,
			IdolName:   cardNameInfo[2],
			Collection: cardNameInfo[3],
			Rarity:     cardNameInfo[4],
			Status:     cardNameInfo[5],
			Skill:      cardNameInfo[6],
			Url:        info.DownloadUrl,
		}
		*cardInfos = append(*cardInfos, cardInfo)
	}
}

func dealMLTDBgInfoByGitee(infos *gitee.FileInfoList, bgInfos *picture.MLTDBgInfoList) {

}

func RandomMLTDCardInfo() picture.MLTDCardInfo {
	return picture.MLTDCardInfos[rand.Intn(len(picture.MLTDCardInfos))]
}

func RandomMLTDBigCardInfo() picture.MLTDCardInfo {
	return picture.MLTDBigCardInfos[rand.Intn(len(picture.MLTDBigCardInfos))]
}

func RandomMLTDBgInfo() picture.MLTDBgInfo {
	return picture.MLTDBgInfos[rand.Intn(len(picture.MLTDBgInfos))]
}
